package com.vfa.vocaburay;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import api.wireless.gdata.parser.ParseException;
import api.wireless.gdata.util.ServiceException;

import com.vfa.data.Entry;
import com.vfa.data.EntryAdapter;
import com.vfa.data.QuizWordsData;
import com.vfa.data.SettingActivity;
import com.vfa.data.SyncDocs;
import com.vfa.data.WordData;
import com.vfa.file.DialogFolder;
import com.vfa.file.DialogFolder.DialogCloseListener;
import com.vfa.file.FileAdapter;
import com.vfa.file.FileInfo;
import com.vfa.file.ListArrayAdapter;
import com.vfa.test.InsertQuestion;
import com.vfa.test.ListCatagory;
import com.vfa.test.QuestionData;

public class BaseImportFile extends Activity implements DialogCloseListener {
	boolean isGoogleDoc = false;
	 public static final int DIALOG_IMPORT = 0;
	 public static final int DIALOG_WAITTING = 1;
	 public static final int DIALOG_AUTHO =2;
	 public static final int DIALOG_RESULT_AUTHO =3;
	 public static final int DIALOG_CONFIRM_QUIZ_EXIST =4;
	 private DialogFolder mDialogFolder;
	 protected static ProgressBar mProgressbarImportFile;
	 
	 protected static TextView mTVStatus;
	 protected static String mStrQuizName = "";
	 private ListView mListFile;
	 private TextView mTVPath;
	 private EditText mETQuizName;
	 Button btImport;
	 Button btBrowser;
	 private FileAdapter mFileAdapter;
	 private String  defaultPath = "/android/data/com.vfa.vocabulary";
	 private String mPath = "";
	 private String dialogmessage = "";
	 
	 private ListArrayAdapter mAdapter;
	 
	 private EntryAdapter entryAdapter;
	 private ArrayList<Entry> listEntry;
	 
	 protected static boolean isImporting = false;
	 protected static boolean isImportSuccess = false;
	 int  UTF8Character = 65279;
	 protected int quizID;
	 //QuestionData questiondata;
	 protected QuizWordsData quizData;
	 int itemcheck;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.importfilescv);
		//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		//
		mETQuizName =  (EditText) findViewById(R.id.etQuizName);
		quizData = new QuizWordsData(getApplicationContext());
		SyncDocs.getIntance().setContext(getApplicationContext());

		
		
		
		mDialogFolder = new DialogFolder(this, this);
       	mDialogFolder.setTitle("Select Folder");
       	
		//questiondata = new QuestionData(this);
		btImport = (Button) findViewById(R.id.btImport);
		btBrowser = (Button) findViewById(R.id.btBrowser);
		mTVPath = (TextView) findViewById(R.id.tvPath);
		//progressbar
		mProgressbarImportFile = (ProgressBar) findViewById(R.id.progressBarImportFile);
		mProgressbarImportFile.setProgress(0);
		mProgressbarImportFile.setVisibility(View.INVISIBLE);
		
		mTVStatus = (TextView) findViewById(R.id.tvStatusImport);
		mTVStatus.setText(" ");
		mTVStatus.setVisibility(View.INVISIBLE);
		mListFile = (ListView) findViewById(R.id.listViewFile);
		
		//mListFile.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice, listFiles));
		//choose single mode
		mListFile.setChoiceMode(1);
		mListFile.setTextFilterEnabled(true);
		mFileAdapter = new FileAdapter(".csv");
		defaultPath = Environment.getExternalStorageDirectory()+ defaultPath;
		//check default path
		File file = new File(defaultPath);
		if(!file.exists() || !file.isDirectory())
		{
			if(!file.mkdir())
			{
				Toast.makeText(getBaseContext(), "can't make default path in sdcard!", Toast.LENGTH_SHORT).show();
				return;
			}
		}
		
		mFileAdapter.getDir(defaultPath,1,false,false);
		mTVPath.setText(defaultPath);
		this.mAdapter = new ListArrayAdapter(this,R.layout.item_choose_single_file,
				mFileAdapter.getFileInfos());
		
		System.out.println(mAdapter.getCount());
		mListFile.setAdapter(mAdapter);
		mListFile.setOnItemClickListener(new OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				ListView temp = (ListView)arg0;
				temp.setItemChecked(arg2, temp.isItemChecked((int)arg3));
			}
			
		});
		btImport.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				doImportPress();
			}
		});
		btBrowser.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mDialogFolder.showDialog();
			}
		});
		ArrayList<Object> conf = (ArrayList<Object>)getLastNonConfigurationInstance();
		if(conf!=null){
			isImporting = (Boolean)conf.get(0);
			isGoogleDoc = (Boolean)conf.get(1);
			String str = (String)conf.get(2);
			mETQuizName.setText(str);
			str = (String)conf.get(3);
			mTVPath.setText(str);
			str = (String)conf.get(4);
			mTVStatus.setText(str);
		}
		else
		{
			if(!isImporting)
				showDialog(DIALOG_IMPORT);
			else{
				mProgressbarImportFile.setVisibility(View.VISIBLE);
				mTVStatus.setVisibility(View.VISIBLE);
			}
			mETQuizName.setText(mStrQuizName);
		}
	}
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if(isImporting)
			setResult(RESULT_OK);
		super.onBackPressed();
	}
	@Override
	public Object onRetainNonConfigurationInstance() {
		// TODO Auto-generated method stub
		ArrayList<Object> temp = new ArrayList<Object>();
		temp.add(isImporting);//0
		temp.add(isGoogleDoc);//1
		temp.add(mETQuizName.getText().toString());//2
		temp.add(mTVPath.getText().toString());//3
		temp.add(mTVStatus.getText().toString());//4
		return temp;
	}
	private Boolean islog = false;	
	private void getDataFromGoogle(){
		
		if (SyncDocs.getIntance().isAuthorize() == false) {
			showDialog(DIALOG_AUTHO);
		}
		else {
			islog=true;
		}
		if(islog == false)
		{return;}
		SyncDocs.getIntance().setContext(getBaseContext());
		AsyncTask<String, String, String> downloadFile = new AsyncTask<String, String, String>(){

			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				showDialog(DIALOG_WAITTING);
			}

			@Override
			protected void onPostExecute(String result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				dismissDialog(DIALOG_WAITTING);
				isGoogleDoc = true;
		    	btBrowser.setVisibility(View.INVISIBLE);
		    	mTVPath.setText("List file in google docs");
				entryAdapter = new EntryAdapter(getBaseContext(),R.layout.item_entry,
						listEntry);
				mListFile.setAdapter(entryAdapter);
			}

			@Override
			protected String doInBackground(String... params) {
				if(!SyncDocs.getIntance().LoadAutho()){
					Toast.makeText(getBaseContext(), "problem when authorizing!", Toast.LENGTH_SHORT).show();
					return"";
				}
		    	
				listEntry = SyncDocs.getIntance().getSpreadEntry();
				return "";

			}
			
		}.execute("");
		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(isImporting){
			mProgressbarImportFile.setVisibility(View.VISIBLE);
			mTVStatus.setVisibility(View.VISIBLE);
		}
		else{
			mTVStatus.setVisibility(View.VISIBLE);
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		
		AlertDialog.Builder dialog =new AlertDialog.Builder(this);
		switch (id) {
		
		case DIALOG_AUTHO:
			 LayoutInflater factoryAutho = LayoutInflater.from(this);
	            final View textEntryView = factoryAutho.inflate(R.layout.login_google, null);
	            dialog.setTitle("Login your account! ");
	            dialog.setView(textEntryView);
	            
	            dialog.setPositiveButton("Login", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	            			final EditText etEmail = (EditText) textEntryView.findViewById(R.id.editText_myEmail);
	                    	final EditText etPass = (EditText) textEntryView.findViewById(R.id.editText_myPass);
	                    	final CheckBox cbShowpass = (CheckBox)textEntryView.findViewById(R.id.checkBox_showpassword_login);
	                    	
	                    	String strEmail =  String.valueOf(etEmail.getText()).trim();
	                    	String strPass =  String.valueOf(etPass.getText()).trim();
	                    	
	                    	cbShowpass.setOnCheckedChangeListener(new  CompoundButton.OnCheckedChangeListener() {
								@Override
								public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
									System.out.println("isChecked show pass = "+isChecked );
									
									if (isChecked) {
										etPass.setInputType(InputType.TYPE_CLASS_TEXT);
									} else {
										etPass.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD);
									}
								}
							});
	                    	
	                        // them catalog
	                    	if(strEmail != "" && strPass!=""){
	                    		if(strEmail.endsWith("@gmail.com")!=true)
	                    		{
	                    			strEmail = strEmail+"@gmail.com";
	                    			System.out.println("email = "+ strEmail);
	                    		}
	                    		try {
	                    			SyncDocs.getIntance().setContext(getApplicationContext());
	                    			SyncDocs.getIntance().Autho(strEmail, strPass);
	                    			
	                    			//showDialog(DIALOG_WAITTING);
	                    			if(SyncDocs.getIntance().isAuthorize()==false)
	                    			{
	                    				dialogmessage = "Login fail ! ";
	                    				showDialog(DIALOG_RESULT_AUTHO);
	                    				System.out.println("login fail");
	                    			}
	                    			else{
	                    				Toast.makeText(getApplicationContext(), "Login success ! ", Toast.LENGTH_SHORT).show();
	                    				islog =true;
	                    				getDataFromGoogle();
	                    				//dismissDialog(DIALOG_WAITTING);
	                    				System.out.println("login ok");
	                    				
	                    				//showstatus.setText("Login your account success. Click Play to export data to google.");
	                    			}
								} catch (Exception e) {
									dialogmessage = "Login fail ! ";
								}
	                    		
	                    		dialog.dismiss();
	                    	}
	                    	else{
	                    		Toast.makeText(getBaseContext(), "Please input value!", Toast.LENGTH_SHORT).show();
	                    	}
	                    	
	                    }
	                });
	                dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {
	                        dialog.dismiss();
	                    }
	                });
	                AlertDialog alertAutho = dialog.create();
	    			return alertAutho;
		
		case DIALOG_RESULT_AUTHO:
			dialog.setTitle(" Notice! ");
			dialog.setMessage(dialogmessage);
			dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			AlertDialog alertresult = dialog.create();
			return alertresult;
			
	    			
		 case DIALOG_WAITTING: {
             ProgressDialog dialogwait = new ProgressDialog(this);
             dialogwait.setMessage("Waiting....!");
             dialogwait.setIndeterminate(true);
             dialogwait.setCancelable(true);
             //dialogwait.
            
             return dialogwait;
         }
		
		case DIALOG_IMPORT:
			 //LayoutInflater factory = LayoutInflater.from(this);
	            //final View textEntryView = factory.inflate(R.layout.login_google, null);
	            dialog.setTitle("Import from ? ");
	           // dialog.setView(textEntryView);
	            
	            dialog.setPositiveButton("Sdcard", new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	            			isGoogleDoc = false;
	            		dialog.dismiss();
	                    }
	                });
	                dialog.setNegativeButton("Google", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {

	                    	if(TestNetworkConnection.getNetworkStatusNoDialog(getBaseContext())==true)
	                    	{
	                    		getDataFromGoogle();
	                    		dialog.dismiss();
	                    	}else {
	                    		Toast.makeText(getApplicationContext(), "Please check your connection ! ", Toast.LENGTH_SHORT).show();
	                    		dialog.dismiss();
							}
	                    }
	                });
	                AlertDialog alert0 = dialog.create();
	    			return alert0;
		case DIALOG_CONFIRM_QUIZ_EXIST:
			// LayoutInflater factory = LayoutInflater.from(this);
			// final View textEntryView = factory.inflate(R.layout.login_google,
			// null);
			dialog.setTitle("The quiz name is existed\n ? ");
			// dialog.setView(textEntryView);
			dialog.setMessage("Do you want to use this name or choose another name?");
			dialog.setPositiveButton("Use it",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							startImport(itemcheck);
						}
					});
			dialog.setNegativeButton("Choose another",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							//set focus edit 
							mETQuizName.setFocusable(true);
							dialog.dismiss();
						}
					});
			AlertDialog alert2 = dialog.create();
			return alert2;
		}
		
		return super.onCreateDialog(id);
	}
	
	protected void DoImport(String filename){
		
	}
	private class DoBackgroundImportFile extends AsyncTask<String, int[], Long>{
		int numOfRecordSuccess = 0;
		int numOfRecordSkip = 0;
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			//showDialog(DIALOG_IMPORT_PROGRESS);
			isImporting = true;
			mProgressbarImportFile.setProgress(0);
			mTVStatus.setText("Importing...");
		}

		@Override
		protected void onPostExecute(Long result) {
			// TODO Auto-generated method stub
			//super.onPostExecute(result);
			isImporting = false;
			Log.d("Import file","finished import");
			mProgressbarImportFile.setProgress(100);
			mProgressbarImportFile.setVisibility(View.GONE);
			//mTVStatus.setVisibility(View.INVISIBLE);
			if(numOfRecordSuccess >0)
				isImportSuccess = true;
				
			if(isImportSuccess )
			{
				setResult(RESULT_OK);
			}
			else
			{
				setResult(RESULT_CANCELED);
			}
			//mProgressDialog.setProgress(100);
			//removeDialog(DIALOG_IMPORT_PROGRESS);
			//dismissDialog(DIALOG_IMPORT_PROGRESS);
			Toast.makeText(getBaseContext(), "finished Import", Toast.LENGTH_SHORT).show();
//			Intent intent = new Intent(ImportFileCSV.this, vfaMain.class);
//			startActivity(intent);
			//ImportFileCSV.this.finish();
		}

		@Override
		protected void onProgressUpdate(int[]... values) {
			// TODO Auto-generated method stub
			Log.d("ANDRp_ASYN",""+values[0]);
			//mProgressDialog.setProgress(values[0]);
			mProgressbarImportFile.setProgress(values[0][0]);
			mTVStatus.setText("Imported "+ values[0][1] + " words, skip "+ values[0][2]  + " ("+((values[0][0] <100) ? values[0][0]:100)+"%)");
		}

		@Override
		protected Long doInBackground(String... params) {
			// TODO Auto-generated method stub
			try {
				readFile(params[0], "English");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		private String[] processString2(String line) {
			// nen dung regular expression??
			ArrayList<String> result = new ArrayList<String>();
			String[] data = line.split("\",\"");
			// remove first " character
			if(data.length >0)
			{
				data[0] = data[0].trim().replace("\"", "");
				//65279
				if(data[0].length() >0)
				{
					int i = data[0].charAt(0);
					if(i == 65279)
						data[0] = data[0].substring(1);
				}
				//data[0] = data[0].replaceAll("\\p{Cntrl}", ""); 
				if(data.length ==5)
				{
					data[4] = data[4].trim();
					data[4] = data[4].substring(0,data[4].length()-1);
					data[4] = data[4].replace("\"\"", "\"");
				}
				else
				{
					if(data.length ==4)
					{
						data[3] = data[3].trim();
						if(data[3].trim().endsWith(","))
							data[3] = data[3].substring(0,data[3].length()-2);
						else
							data[3] = data[3].substring(0,data[3].length()-1);
					}
				}
			}

			return data;

		}
		
		private String[] processString(String line) {
			// nen dung regular expression??
			ArrayList<String> result = new ArrayList<String>();
			String[] data = line.split("\",\"");
			// remove first " character
			for (int i = 0; i < data.length; i++) {
				String temp = data[i];
				while (!temp.endsWith("\"\"") && temp.endsWith("\"")) {
					if (i + 1 < data.length) {
						temp = temp + "\",\"" + data[i + 1];
						i++;
					} else {
						break;
					}

				}
				result.add(temp);
			}
			String[] rs = new String[result.size()];
			for (int i = 0; i < result.size(); i++) {
				rs[i] = result.get(i).replace("\"\"", "\"");
				if (i == 0){
					int k = rs[i].charAt(0);
					if(k == UTF8Character)
						rs[i] = rs[i].substring(1);
					rs[i] = rs[i].substring(1);
				}
				if (i == result.size() - 1) {
					while(rs[i].endsWith(","))
						rs[i] = rs[i].substring(0,rs[i].length()-1);
					rs[i] = rs[i].substring(0, rs[i].length() - 1);
				}
			}
			return rs;

		}

		private void readFile(String filepath, String language) throws IOException {
			// template
		}
		


	}


	@Override
	public void onClose() {
		// TODO Auto-generated method stub
		mPath =  mDialogFolder.getCurPath();
		if(mDialogFolder.getCurPath() == "")
			return;
		mTVPath.setText(mPath);
		mFileAdapter.getDir(mPath,1,false,false);
		this.mAdapter = new ListArrayAdapter(this,R.layout.item_choose_single_file,
				mFileAdapter.getFileInfos());
		mListFile.setAdapter(mAdapter);
		//System.out.println(mAdapter.getCount());
		
	}
	private static final String RELOGIN = "Login with another account";
	
	   @Override
		public boolean onCreateOptionsMenu(Menu menu) {
			// TODO Auto-generated method stub
			super.onCreateOptionsMenu(menu);
			CreateMenu(menu);
			return true;
		}

		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			// TODO Auto-generated method stub
			super.onOptionsItemSelected(item);
			return MenuChoice(item);
		}

		private void CreateMenu(Menu menu)
	    {
	    	menu.add(0, 0, 0, RELOGIN);
	    }
		
	   private boolean MenuChoice(MenuItem item)
	   {
		switch (item.getItemId()) {
		case 0:
			showDialog(DIALOG_AUTHO);
			return true;
		}
		return false;
		   
	   }

	private void doImportPress() {
		itemcheck = mListFile.getCheckedItemPosition();
		if(isImporting == true)
		{
			Log.d("KitVS", "App is importing words");
			return;
		}
		if(itemcheck != -1)
		{
			String quizName = mETQuizName.getText().toString().trim();
			if("".equals(quizName))
			{
				Toast.makeText(getBaseContext(), "Please choose a quiz name for this file ", Toast.LENGTH_SHORT).show();
				// 
				return;
			}
			else{
				// check quiz name co trong db ?
				mStrQuizName = quizName;
				quizID = quizData.getQuizIDbyName(quizName);
				mETQuizName.setFocusable(false);
				if(quizID != -1)
				{
					showDialog(DIALOG_CONFIRM_QUIZ_EXIST);
					return;
				}
				else{
					int rs = quizData.InsertQuizName(quizName);
					if(rs!= -1)
						quizID = quizData.getQuizIDbyName(quizName);
				}
				//insert quiz name vo bang quizs
				//Lay id cua quiznasme nay
				
			}
			
			
			startImport(itemcheck);
			
			//new DoBackgroundImportFile().execute(filenameChoose.mFilePath);
		}
		else
		{
			Toast.makeText(getBaseContext(), "Please choose  a  file to import!", Toast.LENGTH_SHORT).show();
		}
	}

	private void startImport(int itemcheck) {
		mProgressbarImportFile.setVisibility(View.VISIBLE);
		mTVStatus.setVisibility(View.VISIBLE);
		String path = "";
		if(isGoogleDoc)
		{
			//down ve file roi import;
			final Entry entryChoose = (Entry)mListFile.getItemAtPosition(itemcheck);
			AsyncTask<String, String, String> downloadFile = new AsyncTask<String, String, String>(){

				@Override
				protected void onPreExecute() {
					// TODO Auto-generated method stub
					super.onPreExecute();
					showDialog(DIALOG_WAITTING);
				}

				@Override
				protected void onPostExecute(String result) {
					// TODO Auto-generated method stub
					super.onPostExecute(result);
					dismissDialog(DIALOG_WAITTING);
					DoImport(result);
				}

				@Override
				protected String doInBackground(String... params) {
					try {
						return SyncDocs.getIntance().downloadSpread(entryChoose.getId());
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ServiceException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					return "";

				}
				
			}.execute("");
			
			
		}else{
			FileInfo filenameChoose = (FileInfo)mListFile.getItemAtPosition(itemcheck);
			path = filenameChoose.mFilePath;
			DoImport(path);
		}
	}   

}
